package com.yks.rpc.transport;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

public class TransportServer {
    /**
     * 基于jetty
     */
    private Server server;

    public void init(int port) {
        this.server = new Server(port);

        //servlet接受请求
        ServletContextHandler ctx = new ServletContextHandler();

        ServletHolder holder = new ServletHolder(new RequestServlet());
        ctx.addServlet(holder,"/*");
        server.setHandler(ctx);
    }

    public void start() {
        try {
            server.start();
            server.join();
        } catch (Exception e) {
            System.out.println("server 启动异常");
        }
    }


    class RequestServlet extends HttpServlet {
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            InputStream inputStream = req.getInputStream();
            ServletOutputStream outputStream = resp.getOutputStream();

            outputStream.flush();
        }

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            super.doGet(req, resp);
        }
    }
}
